<?php

namespace lc\wechat\wxpay\database;

use lc\helpers\Helper;
use lc\wechat\wxpay\base\WxPayConfig;
use lc\wechat\wxpay\base\WxPayException;

/**
 * @desc    接口调用结果类 Results
 * @package lc\wxpay\database
 */
class Results extends Base
{
    /**
     * @desc    检测签名
     * @return  bool
     * @throws  WxPayException
     */
    public function checkSign()
    {
        if (!$this->isSignSet()) {
            throw new WxPayException('签名错误.');
        }

        $sign = Helper::makeSign($this->getValues(), WxPayConfig::$key);
        if ($this->getSign() == $sign) {
            return true;
        }
        throw new WxPayException('签名错误.');
    }

    /**
     * 使用数组初始化
     * @param array $array
     */
    public function fromArray($array)
    {
        $this->values = $array;
    }

    /**
     * @desc    设置参数
     * @param   string $key
     * @param   string $value
     */
    public function setData($key, $value)
    {
        $this->values[$key] = $value;
    }

    /*
     * @desc    将xml转为array
     * @param   $xml
     * @param   bool $check
     * @return  array
     */
    public static function init($xml, $check = true)
    {
        $obj = new self();
        $obj->values = Helper::xmlToArray($xml);
        if ($obj->values['return_code'] != 'SUCCESS') {
            return $obj->getValues();
        }
        if ($check) {
            $obj->checkSign();
        }
        return $obj->getValues();
    }
}